package com.lwq.imserver.advice;

import com.lwq.imserver.exception.AuthenticationException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2022/1/26 10:18
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class ExceptionAdvice {

    /**
     * 全局捕获401异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<?> authenticationException(Exception e){
        if(e instanceof AuthenticationException){
            return new ResponseEntity<>(StringUtils.isEmpty(e.getMessage()) ? "验证失败" : e.getMessage(),
                    HttpStatus.UNAUTHORIZED);
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    /**
     * 全局捕获500异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<?> apiException(Exception e){
        if(e instanceof RuntimeException){
            return new ResponseEntity<>(StringUtils.isEmpty(e.getMessage()) ? "系统繁忙" : e.getMessage(),
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
        this.log.error("服务端出现500异常---------------->");
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}
